﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace Cfg.Proxies
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T">Proxy type</typeparam>
    public class CfgScope<T> : ICfgScope, IDisposable
    {
        private readonly CfgScope<T> _parentScope;

        private readonly Dictionary<string, object> _overrides = new Dictionary<string, object>(); 

        public CfgScope()
        {
            _parentScope = WebSafeCallContext.GetData(ProxyBase.CurrentScopeKey) as CfgScope<T>;
            WebSafeCallContext.SetData(ProxyBase.CurrentScopeKey, this);
        }

        public CfgScope<T> Override<TProp>(Expression<Func<T, TProp>> predicate, TProp scopeValue)
        {
            var expression = predicate.ToString();
            var i = expression.IndexOf('.')+1;
            var key = expression.Substring(i);

            _overrides[key] = scopeValue;
            return this;
        }


        public void Dispose()
        {
            if (_parentScope == null)
                WebSafeCallContext.FreeNamedDataSlot(ProxyBase.CurrentScopeKey);
            else
                WebSafeCallContext.SetData(ProxyBase.CurrentScopeKey, _parentScope);
        }

        public bool HasValue(string key)
        {
            return _overrides.ContainsKey(key);
        }

        public TProp GetValue<TProp>(string key)
        {
            return (TProp) _overrides[key];
        }
    }
}
